<template>
  <div class="user-service-admin">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <div class="header-left">
        <h2>客户服务管理</h2>
        <el-tag type="info">在线客服: {{ onlineAdmins }}</el-tag>
        <el-tag type="success">在线用户: {{ onlineUsers }}</el-tag>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名称或消息内容"
          prefix-icon="Search"
          style="width: 300px; margin-right: 12px;"
          clearable
        />
        <el-button type="primary" icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧用户列表 -->
      <div class="conversation-list">
        <div class="list-header">
          <span>在线用户列表</span>
          <el-tag type="success">{{ onlineUsersList.length }} 人在线</el-tag>
        </div>

        <div class="conversation-items">
          <div
            v-for="user in filteredOnlineUsers"
            :key="user.userId"
            :class="['conversation-item', { 
              active: selectedUserId === user.userId, 
              unread: user.unreadCount > 0 
            }]"
            @click="selectUser(user)"
          >
            <div class="item-avatar">
              <el-avatar :size="40" :src="user.avatar || '/images/mihoyo.jpg'" />
              <div v-if="user.unreadCount > 0" class="unread-badge">
                {{ user.unreadCount }}
              </div>
            </div>
            <div class="item-content">
              <div class="user-name">
                {{ user.nickName }}
                <el-tag v-if="user.status === 'active'" size="small" type="success">在线</el-tag>
                <el-tag v-else size="small" type="info">离线</el-tag>
              </div>
              <div class="last-message">{{ user.lastMessage || '暂无消息' }}</div>
              <div class="time">{{ formatTime(user.lastMessageTime) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-panel">
        <div v-if="selectedUser" class="chat-container">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="header-info">
              <el-avatar :size="40" :src="selectedUser.avatar || '/images/mihoyo.jpg'" />
              <div class="user-info">
                <h4>{{ selectedUser.nickName }}</h4>
                <p>用户ID: {{ selectedUser.userId }}</p>
              </div>
            </div>
            <div class="header-actions">
              <el-button size="small" icon="View" @click="viewUserInfo">查看用户信息</el-button>
              <el-button size="small" icon="Close" @click="endConversation">结束对话</el-button>
            </div>
          </div>

          <!-- 消息区域 -->
          <div class="messages-container" ref="messagesContainer">
            <div
              v-for="(message, index) in currentMessages"
              :key="index"
              :class="['message', message.senderType === 'user' ? 'user-message' : 'admin-message']"
            >
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ formatMessageTime(message.timestamp) }}</div>
              </div>
              <el-avatar 
                :size="32" 
                :src="message.senderType === 'user' ? (selectedUser.avatar || '/images/mihoyo.jpg') : userInfo.icon" 
              />
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <el-input
              v-model="replyMessage"
              type="textarea"
              :rows="3"
              placeholder="输入回复内容..."
              resize="none"
              @keydown.enter.prevent="handleSendMessage"
            />
            <div class="input-actions">
              <div class="quick-replies">
                <el-button
                  v-for="(reply, index) in quickReplies"
                  :key="index"
                  size="small"
                  @click="useQuickReply(reply)"
                >
                  {{ reply }}
                </el-button>
              </div>
              <el-button type="primary" :loading="sending" @click="handleSendMessage">
                发送
              </el-button>
            </div>
          </div>
        </div>

        <div v-else class="empty-state">
          <el-empty description="请选择左侧的用户开始聊天" />
        </div>
      </div>
    </div>

    <!-- 用户信息弹窗 -->
    <el-dialog v-model="userDialogVisible" title="用户信息" width="600px">
      <div v-if="selectedUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ selectedUser.userId }}</el-descriptions-item>
          <el-descriptions-item label="用户昵称">{{ selectedUser.nickName }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="selectedUser.status === 'active' ? 'success' : 'info'">
              {{ selectedUser.status === 'active' ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAdminStore } from '@/stores/modules/admin'
import { endChatRoom, getUserChatHistory } from '@/api/chat'

// 存储数据
const onlineUsersList = ref([])
const currentMessages = ref([])
const selectedUser = ref(null)
const selectedUserId = ref(null)
const messagesContainer = ref(null) // 添加消息容器引用
const searchKeyword = ref('')
const replyMessage = ref('')
const sending = ref(false)
const userDialogVisible = ref(false)
const onlineAdmins = ref(0)
const onlineUsers = ref(0)

const quickReplies = [
  '您好，请问有什么可以帮您？',
  '请稍等，我帮您查询一下',
  '感谢您的耐心等待',
  '请问还有其他问题吗？'
]

// 监听消息变化，自动滚动到底部
watch(currentMessages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 计算属性
const filteredOnlineUsers = computed(() => {
  let filtered = onlineUsersList.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.nickName.toLowerCase().includes(keyword) ||
      (user.lastMessage && user.lastMessage.toLowerCase().includes(keyword))
    )
  }
  
  return filtered.sort((a, b) => b.lastMessageTime - a.lastMessageTime)
})

const userInfo = ref({
  nickName: '客服管理员',
  icon: '/images/mihoyo.jpg'
})

// WebSocket 实例
const socket = ref(null)
const adminStore = useAdminStore()

// 初始化 WebSocket 连接
const initWebSocket = () => {
  const token = adminStore.accessToken || ''
  // 根据您的后端配置调整 WebSocket URL
  socket.value = new WebSocket(`ws://localhost:8080/api/chat/admin?token=${encodeURIComponent(token)}`)

  socket.value.onopen = () => {
    console.log('WebSocket 已连接')
    ElMessage.success('已连接到聊天服务器')
    
    // 发送管理员上线通知
    const loginMessage = {
      type: 'admin_online',
      adminId: adminStore.adminInfo
    }
    socket.value.send(JSON.stringify(loginMessage))
  }

  socket.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log('收到消息:', data)
      console.log('消息类型:', data.type)
      // 根据消息类型处理不同的业务逻辑
      switch(data.type) {
        case 'onlineUsers':
          // 收到在线用户列表
          handleOnlineUsers(data.users)
          break
        case 'newUser':
          // 新用户上线
          handleNewUser(data)
          break
        case 'userDisconnected':
          // 用户下线
          handleUserDisconnected(data.userId)
          break
        case 'message':
          // 收到新消息
          handleNewMessage(data)
          break
        default:
          console.log('未知消息类型:', data.type)
      }
    } catch (error) {
      console.error('解析消息错误:', error)
    }
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket 错误:', error)
    ElMessage.error('连接发生错误')
  }

  socket.value.onclose = () => {
    console.log('WebSocket 已关闭')
    ElMessage.warning('连接已断开')
  }
}

// 处理在线用户列表
const handleOnlineUsers = (userIds) => {
  onlineUsers.value = userIds.length
  // 更新在线用户列表
  onlineUsersList.value = userIds.map(userId => ({
    userId,
    nickName: `用户${userId}`,
    status: 'active',
    unreadCount: 0,
    lastMessage: '',
    lastMessageTime: Date.now()
  }))
}

// 处理新用户上线
const handleNewUser = (data) => {
  const { userId, nickName } = data
  onlineUsers.value++
  
  // 添加到在线用户列表
  const existingUser = onlineUsersList.value.find(user => user.userId === userId)
  if (!existingUser) {
    onlineUsersList.value.push({
      userId,
      nickName: nickName || `用户${userId}`,
      status: 'active',
      unreadCount: 0,
      lastMessage: '',
      lastMessageTime: Date.now()
    })
  }
  
  ElMessage.info(`新用户 ${nickName} 已上线`)
}

// 处理用户下线
const handleUserDisconnected = (userId) => {
  onlineUsers.value--
  const userIndex = onlineUsersList.value.findIndex(user => user.userId === userId)
  if (userIndex !== -1) {
    onlineUsersList.value[userIndex].status = 'offline'
    ElMessage.info(`用户 ${onlineUsersList.value[userIndex].nickName} 已下线`)
  }
}

// 处理新消息 - 修复版本
const handleNewMessage = (data) => {
  const { fromId, content, timestamp } = data
  console.log('收到新消息:', data)
  
  // 确定发送者类型
  const senderType = "user"
  
  // 如果是当前选中的用户发来的消息
  if (selectedUserId.value == fromId) {
    currentMessages.value.push({
      senderType: senderType,
      content,
      timestamp: timestamp || Date.now()
    })
  } else {
    // 更新其他用户的未读消息数
    const user = onlineUsersList.value.find(u => u.userId == fromId)
    if (user) {
      user.unreadCount = (user.unreadCount || 0) + 1
      user.lastMessage = content
      user.lastMessageTime = timestamp || Date.now()
      ElMessage.info(`收到来自 ${user.nickName} 的新消息`)
    }
  }
}

// 选择用户开始聊天
const selectUser = async (user) => {
  selectedUser.value = user
  selectedUserId.value = user.userId
  user.unreadCount = 0
  currentMessages.value = []
  
  // 加载聊天历史
  await loadChatHistory(user.userId)
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}
// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}
// 加载聊天历史 - 修复版本
const loadChatHistory = async (userId) => {
  try {
    const res = await getUserChatHistory(userId)
    console.log('查询与该用户的历史聊天记录', res)
    
    if (res && Array.isArray(res)) {
      currentMessages.value = res.map(item => ({
        senderType: item.fromType, // 根据您的API调整
        content: item.content,
        timestamp: item.createTime || item.timestamp || Date.now()
      }))
    }
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    ElMessage.error('加载聊天历史失败')
  }
}

// 发送消息 - 修复版本
const handleSendMessage = async () => {
  if (!replyMessage.value.trim() || !selectedUser.value) return
  
  sending.value = true
  try {
    const messageData = {
      type: 'message',
      toId: selectedUserId.value,
      content: replyMessage.value.trim(),
      timestamp: Date.now()
    }

    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      socket.value.send(JSON.stringify(messageData))
      
      // 立即显示发送的消息
      currentMessages.value.push({
        senderType: 'admin',
        content: replyMessage.value.trim(),
        timestamp: Date.now()
      })

      // 更新用户最后消息
      const user = onlineUsersList.value.find(u => u.userId == selectedUserId.value)
      if (user) {
        user.lastMessage = replyMessage.value.trim()
        user.lastMessageTime = Date.now()
      }

      replyMessage.value = ''
    } else {
      throw new Error('WebSocket 未连接')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请检查网络连接')
  } finally {
    sending.value = false
  }
}

// 结束对话
const endConversation = () => {
  if (selectedUser.value) {
    ElMessageBox.confirm('确定要结束与这个用户的对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const messageData = {
          type: 'admin_close',
          toId: selectedUserId.value.trim(),
          content: '客服已关闭',
          timestamp: Date.now()
      }
      console.log('发送关闭消息:', messageData)
      socket.value.send(JSON.stringify(messageData))
      // 结束会话
      endChatRoom(selectedUserId.value).then(() => {
        
        
        selectedUser.value = null
        selectedUserId.value = null
        currentMessages.value = []
        ElMessage.success('对话已结束')
      })
    })
  }
}

const useQuickReply = (reply) => {
  replyMessage.value = reply
}

const refreshData = () => {
  // 重新连接WebSocket
  if (socket.value) {
    socket.value.close()
  }
  initWebSocket()
  ElMessage.success('数据已刷新')
}

const viewUserInfo = () => {
  userDialogVisible.value = true
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

const formatMessageTime = (time) => {
  return new Date(time).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 生命周期
onMounted(() => {
  initWebSocket()
})

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
})
</script>


<style lang="scss" scoped>
.user-service-admin {
  height: 85vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-header {
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  flex-shrink: 0;
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  height: 100%;
  min-height: 0;
}

.conversation-list {
  width: 320px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
  min-height: 0;
  .list-header {
    padding: 16px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
    font-weight: 500;
    flex-shrink: 0;
  }
  
  .conversation-items {
    flex: 1;
    overflow-y: auto;
    min-height: 0;
    .conversation-item {
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      display: flex;
      gap: 12px;
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        background-color: #ecf5ff;
        border-right: 3px solid #409eff;
      }
      
      &.unread {
        background-color: #f0f9ff;
      }
      
      .item-avatar {
        position: relative;
        
        .unread-badge {
          position: absolute;
          top: -4px;
          right: -4px;
          background: #f56c6c;
          color: white;
          border-radius: 10px;
          min-width: 18px;
          height: 18px;
          line-height: 18px;
          text-align: center;
          font-size: 12px;
          padding: 0 4px;
        }
      }
      
      .item-content {
        flex: 1;
        min-width: 0;
        
        .user-name {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 500;
          margin-bottom: 4px;
          
          :deep(.el-tag) {
            height: 20px;
            line-height: 18px;
          }
        }
        
        .last-message {
          color: #606266;
          font-size: 13px;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .time {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
  
  .chat-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
    flex-shrink: 0;
    .header-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .user-info {
        h4 {
          margin: 0 0 4px 0;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
  
  .messages-container {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    min-height: 50vh;
    background: #f8f9fa;
    max-height: fit-content;
    .message {
      display: flex;
      margin-bottom: 16px;
      gap: 12px;
      
      &.user-message {
        flex-direction: row;
        
        .message-content {
          background: #fff;
          border: 1px solid #e4e7ed;
        }
      }
      
      &.admin-message {
        flex-direction: row-reverse;
        
        .message-content {
          background: #409eff;
          color: white;
        }
      }
      
      .message-content {
        max-width: 60%;
        padding: 12px 16px;
        border-radius: 12px;
        background-color: #eee;
        
        .message-text {
          margin-bottom: 4px;
          line-height: 1.5;
        }
        
        .message-time {
          font-size: 12px;
          opacity: 0.7;
        }
      }
    }
  }
  
  .input-area {
    // 输入区域固定高度
    flex-shrink: 0;
    padding: 16px 20px;
    border-top: 1px solid #e6e6e6;
    background: #fff;
    flex-shrink: 0;
    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;
      
      .quick-replies {
        display: flex;
        gap: 8px;
        
        :deep(.el-button) {
          height: 28px;
          padding: 0 12px;
          font-size: 12px;
        }
      }
    }
  }
  
  .empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fafafa;
  }
}

.user-detail {
  padding: 20px 0;
}

// 滚动条样式
.conversation-items::-webkit-scrollbar,
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.conversation-items::-webkit-scrollbar-track,
.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.conversation-items::-webkit-scrollbar-thumb,
.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.conversation-items::-webkit-scrollbar-thumb:hover,
.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>